package com.jt.zcdemo;


import com.microsoft.playwright.*;
import com.microsoft.playwright.options.ColorScheme;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlaywrightUtil {

    private static Map<String, String> buildEnvMap(){
        Map<String, String> map = new HashMap<String, String>();
        // 跳过下载浏览器，因为公司是内网，这个配置很重要
        //map.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "0");
        map.put("PLAYWRIGHT_BROWSERS_PATH", "D:\\google");
        return map;
    }



    public static String get(String url, boolean openWindow) {
        Playwright playwright = null;
        Browser browser = null;
        String content = null;
        try {
            Map<String, String> map = buildEnvMap();
            playwright = Playwright.create(new Playwright.CreateOptions().setEnv(map));
            browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(!openWindow) // 取消无头模式，我们才能看见浏览器操作
                    .setSlowMo(1000) // 减慢执行速度，以免太快
                    .setDevtools(true));
            BrowserContext browserContext = browser
                    .newContext(new Browser.NewContextOptions().setColorScheme(ColorScheme.DARK) // 设置浏览器主题，chromium设置了dark好像没用
                            .setViewportSize(100, 100) // 设置浏览器打开后窗口大小
                    );
            Page page = browserContext.newPage();
            page.navigate(url);

            content = page.content();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (browser != null) {
                browser.close();

            }
            if (playwright != null) {
                playwright.close();
            }
        }
        return content;
    }





    public static void main(String[] args) throws MalformedURLException {
        String url = "https://live.douyin.com/169346678496";
        String html = PlaywrightUtil.get(url, false);
        Pattern pattern = Pattern.compile("(https://pull-[^\"\\s,]+)");
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            String rawUrl = matcher.group(1);
            System.out.println("获取到视频源地址：" + rawUrl.replace("&amp;", "&").replaceAll("&quot;|\"", ""));
        }
    }
}
